package com.sms.riskservice.aspect;

import cn.hutool.core.util.StrUtil;
import com.sms.common.exception.SmsException;
import com.sms.common.result.ResultCode;
import com.sms.riskservice.service.SmsRiskService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Arrays;

@Slf4j
@Aspect
@Component
public class SmsRiskAspect {
    
    @Autowired
    private SmsRiskService smsRiskService;
    
    /**
     * 短信发送前的风控检查
     * 通过手机号参数串联，形成完整的校验链路
     */
    @Before("@annotation(com.sms.riskservice.annotation.SmsRiskCheck)")
    public void beforeSmsSend(JoinPoint joinPoint) {
        log.info("开始执行短信风控检查");
        
        // 获取方法参数
        Object[] args = joinPoint.getArgs();
        String phoneNumber = extractPhoneNumber(args);
        
        if (StrUtil.isBlank(phoneNumber)) {
            throw new SmsException(ResultCode.PARAM_ERROR, "手机号不能为空");
        }
        
        // AOP层面的通用风控检查
        performGeneralRiskCheck(phoneNumber);
        
        log.info("短信风控检查通过，手机号: {}", phoneNumber);
    }
    
    /**
     * 提取手机号参数
     */
    private String extractPhoneNumber(Object[] args) {
        if (args == null || args.length == 0) {
            return null;
        }
        
        // 遍历参数，查找手机号
        for (Object arg : args) {
            if (arg instanceof String) {
                String str = (String) arg;
                if (isPhoneNumber(str)) {
                    return str;
                }
            }
        }
        
        return null;
    }
    
    /**
     * 判断是否为手机号
     */
    private boolean isPhoneNumber(String str) {
        return str != null && str.matches("^1[3-9]\\d{9}$");
    }
    
    /**
     * 执行通用风控检查
     */
    private void performGeneralRiskCheck(String phoneNumber) {
        // 1. 检查黑名单
        if (smsRiskService.isInBlacklist(phoneNumber)) {
            throw new SmsException(ResultCode.SMS_PHONE_BLACKLISTED, "手机号在黑名单中");
        }
        
        // 2. 检查发送频率
        if (smsRiskService.isRateLimitExceeded(phoneNumber)) {
            throw new SmsException(ResultCode.SMS_RATE_LIMIT_EXCEEDED, "发送频率超限");
        }
        
        // 3. 检查用户状态
        if (smsRiskService.isUserBlocked(phoneNumber)) {
            throw new SmsException(ResultCode.RISK_USER_BLOCKED, "用户已被风控拦截");
        }
        
        // 4. 检查位置异常
        if (smsRiskService.isLocationSuspicious(phoneNumber)) {
            throw new SmsException(ResultCode.RISK_LOCATION_SUSPICIOUS, "用户位置异常");
        }
    }
} 